/**
 * 系统名称: 企业财资
 * 模块名称: repair-boot
 * 类 名 称: WeChatAuthenticationcom.mt.common.system.entity.ScheduledTaskLog.java
 * 软件版权: 恒生电子股份有限公司
 * 修改记录:
 * 修改人员:
 * 修改说明:
 * ============ ============================================
 * zhanghong 创建
 * ============ ============================================
 */
package com.mt.common.core.security;

import com.mt.common.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 *
 *
 * @author zhanghong
 * @date 2023-03-13 23:44
 */
public class WeChatAuthenticationProvider implements AuthenticationProvider {


    @Autowired
    private UserService userService;
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        if (authentication.isAuthenticated()) {
            return authentication;
        }
        //获取过滤器封装的token信息
        WeChatAuthenticationToken authenticationToken = (WeChatAuthenticationToken) authentication;
        String openid = (String)authenticationToken.getPrincipal();
        //查询到用户
        UserDetails user=this.userService.getByOpenID(openid);
        if(null==user){
            //微信账号没有关联网站账号
            throw new UsernameNotFoundException("微信授权openid无效，请重新登陆");
        }
        UsernamePasswordAuthenticationToken authenticationResult=new UsernamePasswordAuthenticationToken(user,user.getPassword(),user.getAuthorities());
        return authenticationResult;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return WeChatAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
